﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ScreenShotDemo
{
    /// <summary>
    /// 轮询任务
    /// </summary>
    public class TaskHepler
    {
        private static CancellationTokenSource? _cancellationTokenSource;
        private static TaskHepler? _instance;
        public delegate void TaskDelegate();
        public static TaskHepler GetTaskHepler()
        {
            if (_instance != null)
            {
                return _instance;
            }
            else {
                return new TaskHepler();
            }   
        }
        /// <summary>
        /// 初始化轮询任务
        /// </summary>
        public TaskHepler()
        {
            _cancellationTokenSource = new CancellationTokenSource();
            _instance = this;
        }
        /// <summary>
        /// 执行轮询任务
        /// </summary>
        /// <param name="taskDelegate"></param>
        public void StartTask(TaskDelegate taskDelegate) 
        {
            Task.Run(async () => {
                while (!_cancellationTokenSource.Token.IsCancellationRequested) {
                    // 轮询任务
                    taskDelegate();
                    await Task.Delay(1000, _cancellationTokenSource.Token);
                }
            }, _cancellationTokenSource.Token);
        }

        public static void Dispose()
        {
            _cancellationTokenSource?.Cancel();
            _cancellationTokenSource?.Dispose();
        }
    }
}
